package com.lanhai.agv.pos;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
 

public class PosDBHelper {

	public PosDBHelper() throws Exception {

		Class.forName("com.mysql.cj.jdbc.Driver");

	}

	public void logAgv(List<AgvPosItem> list) {
		if (list == null || list.size() == 0)
			return;
		List<AgvPosItem> tmp = new ArrayList<AgvPosItem>();

		for (int i = 0; i < list.size(); i++) {
			tmp.add(list.get(i));
			if (i % 100 == 0) {
				List<String> sqllist = createAgvSql(tmp);
				tmp.clear();
				doSql(sqllist);
			}
		}
		if (tmp.size() > 0) {
			List<String> sqllist = createAgvSql(tmp);

			doSql(sqllist);
		}
	}

	private List<String> createAgvSql(List<AgvPosItem> list) {
		List<String> ls = new ArrayList<String>();

		String s = "";
		for (AgvPosItem d : list) {
			s = String.format("update agv_pos set x=%d,y=%d,lv=%d where agvid=%d;", d.getX(), d.getY(), d.getLv(),
					d.getAgvid());
			ls.add(s);
		}
		return ls;
	}

	boolean doSql(List<String> sqllist) {
		boolean success = false;
		Statement statement = null;
		Connection connection = null;
		try {
			connection = DriverManager.getConnection("数据库连接", "用户名", "密码");
			statement = connection.createStatement();
			for (String sql : sqllist) {
				statement.execute(sql);
			}

			success = true;
		} catch (Exception er) {

		} finally {
			try {
				if (statement != null) {
					statement.close();
				}
			} catch (Exception m1) {
			}
			try {
				if (connection != null) {
					connection.close();
				}
			} catch (Exception m2) {
			}
		}
		return success;
	}

}
